package com.mvvm.start.main.utils;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import org.xml.sax.XMLReader;

import java.util.ArrayList;
import java.util.Locale;

/**
 * @功能:
 * @User Lmy
 * @Creat 2023/3/20 14:16
 */
public class DetailTagHandler implements Html.TagHandler {

    private Context context;

    private ArrayList<String> strings;

    public DetailTagHandler(Context context) {

        this.context = context;
        strings = new ArrayList<String>();
    }

    @Override

    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        Log.e("handleTag--->", "tag:" + tag+"tag.toLowerCase(Locale.getDefault())-->"+tag.toLowerCase(Locale.getDefault()));
        // 处理标签
        if ("img".equals(tag.toLowerCase(Locale.getDefault()))) {
            // 获取长度
            int len = output.length();

            // 获取图片地址
            ImageSpan[] images = output.getSpans(len - 1, len, ImageSpan.class);

            String imgURL = images[0].getSource();

            // 记录所有图片地址
            strings.add(imgURL);
            // 记录是第几张图片
            int position = strings.size() - 1;
            // 使图片可点击并监听点击事件
            output.setSpan(new ClickableImage(context, position), len - 1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }
        if ("font".equals(tag.toLowerCase(Locale.getDefault()))) {
            int len = output.length();
            // 获取图片地址
//            ImageSpan[] images = output.getSpans(len - 1, len, ImageSpan.class);
//            String imgURL = images[0].getSource();
//            // 记录所有图片地址
//            strings.add(imgURL);
//            // 记录是第几张图片
//            int position = strings.size() - 1;
            // 使图片可点击并监听点击事件
//            output.setSpan(new ClickableImage(context, position), len - 1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }


    }

    private class ClickableImage extends ClickableSpan {

        private Context context;

        private int position;
        public ClickableImage(Context context, int position) {

            this.context = context;
            this.position = position;
        }
        @Override

        public void onClick(View widget) {
            Toast.makeText(context, strings.get(position), Toast.LENGTH_SHORT).show();
        }

    }
    private class ClickableText extends ClickableSpan {

        private Context context;

        private int position;
        public ClickableText(Context context, int position) {

            this.context = context;
            this.position = position;
        }
        @Override

        public void onClick(View widget) {
            Toast.makeText(context, strings.get(position), Toast.LENGTH_SHORT).show();
        }

    }
}
